package com.zdsoft.blp.zongbuju.wode.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.zdsoft.blp.R;
import com.zdsoft.blp.gongyong.API.API;
import com.zdsoft.blp.gongyong.application.MyApp;
import com.zdsoft.blp.gongyong.fanhui.FanHuiView;
import com.zdsoft.blp.gongyong.imageTrans.CircleImage;
import com.zdsoft.blp.gongyong.net.BaseActivity;
import com.zdsoft.blp.gongyong.net.Net;
import com.zdsoft.blp.gongyong.net.NetCallback;
import com.zdsoft.blp.gongyong.upLoad.Base64ToString;
import com.zdsoft.blp.zongbuju.MainActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2016/9/1.
 */
public class GeRenXinXiActivity extends BaseActivity implements View.OnClickListener, NetCallback {

    private FanHuiView back;
    private LinearLayout ll_xiugai;
    private LinearLayout ll_mima;
    private Button bt_tcdl;
    private TextView tv_xgname;
    private ImageView iv_touxiang;
    private PopupWindow popupWindow;
    private SharedPreferences sp;
    private EditText et_phoneNumber;
    private static final Integer NICKNAMESAVE = 1;
    private static final Integer HUOQUINFO =2;
    private static final Integer UPLOADHEAD =3;
    private Bitmap photo;
    @Override
    protected void init() {
        setContentView(R.layout.gerenxinxi_wode);
        ll_mima = find(R.id.ll_mima);
        bt_tcdl = find(R.id.bt_tcdl);
        ll_xiugai = find(R.id.ll_xiugai);
        iv_touxiang = find(R.id.iv_touxiang);
        tv_xgname = find(R.id.tv_xgname);
        et_phoneNumber = find(R.id.et_phoneNumber);
        back = find(R.id.back);
        sp = getSharedPreferences("info", Context.MODE_PRIVATE);
        back.getTv_title().setText("个人信息");
        //设置信息
        setInfo();
        ll_xiugai.setOnClickListener(this);
        ll_mima.setOnClickListener(this);
        iv_touxiang.setOnClickListener(this);
        bt_tcdl.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.ll_xiugai:
                intent = new Intent(getApplicationContext(), XiuGaiNiChengActivity.class);
                String nicheng = tv_xgname.getText().toString().trim();
                intent.putExtra("nicheng", nicheng);
                startActivityForResult(intent, 1);
                break;
            case R.id.ll_mima:
                intent = new Intent(getApplicationContext(), XiuGaiMiMaActivity.class);
                startActivity(intent);
                break;
            case R.id.bt_tcdl:

                GeRenXinXiActivity.this.finish();
                SharedPreferences.Editor editor = sp.edit();
                editor.putBoolean("isLoginSuccess", false);
                editor.commit();
                break;
            case R.id.iv_touxiang:
                getPopupWindow();
                backgroundAlpha();
                // 这里是位置显示方式,在屏幕的上侧
                popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    String name = data.getStringExtra("name");
                    if (!"".equals(name) && !tv_xgname.getText().toString().equals(name)) {
                        setNickName(name);
                        tv_xgname.setText(name);
                    }
                }
                break;
            case 2:
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) && resultCode != RESULT_CANCELED) {
                    File tempFile = new File(Environment.getExternalStorageDirectory() + "/" + "asd.jpg");
                    startPhotoZoom(Uri.fromFile(tempFile));
                } else {
                    Toast.makeText(getApplicationContext(), "未找到存储卡，无法存储照片！", Toast.LENGTH_LONG).show();
                }
                break;
            case 3:
                if (resultCode != RESULT_CANCELED) {
                    startPhotoZoom(data.getData());
                }
                break;
            case 4:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    if (extras != null) {
                        photo = extras.getParcelable("data");
                        String file =Base64ToString.toString(photo);
                        String userId = sp.getString("userId", "no");
                        if(!"".equals(file)&&file!=null&&!"no".equals(userId)){
                            Net net = new Net();
                            net.url = API.MEMBER_URL;
                            net.nameSpace = API.MEMBER_NAMESPACE;
                            net.methodName = API.UPLOADHEAD;
                            Map<String, Object> map = new HashMap<>();
                            map.put("userId", userId);
                            map.put("fileName", "aaa.jpg");
                            map.put("file", file);
                            net.parms = map;
                            net.code =UPLOADHEAD ;
                            getServer(net, this);
                        }
                    }
                    dissmiss();
                }
                break;

        }
    }

    protected void initPopuptWindow() {
        // TODO Auto-generated method stub
        // 获取自定义布局文件activity_popupwindow_left.xml的视图
        View popupWindow_view = getLayoutInflater().inflate(R.layout.xztouxianglayout, null, false);
        Button bt_cancel = (Button) popupWindow_view.findViewById(R.id.bt_cancel);
        Button bt_select = (Button) popupWindow_view.findViewById(R.id.bt_select);
        Button bt_camera = (Button) popupWindow_view.findViewById(R.id.bt_camera);
        bt_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dissmiss();
            }
        });

        bt_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                // 判断存储卡是否可以用，可用进行存储
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT,
                            Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "asd.jpg")));
                }
                startActivityForResult(intentFromCapture, 2);
            }
        });
        bt_select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intentFromGallery = new Intent();
                intentFromGallery.setType("image/*"); // 设置文件类型
                intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intentFromGallery, 3);
            }
        });

        // 创建PopupWindow实例,200,LayoutParams.MATCH_PARENT分别是宽度和高度
        popupWindow = new PopupWindow(popupWindow_view, ViewGroup.LayoutParams.MATCH_PARENT, 500, true);

    }

    //让pop消失
    private void dissmiss() {
        popupWindow.dismiss();
        popupWindow = null;
        dismissBackgroundAlpha();
    }

    private void getPopupWindow() {
        if (null != popupWindow) {
            popupWindow.dismiss();
            return;
        } else {
            initPopuptWindow();
        }
    }

    public void backgroundAlpha() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = (float) 0.5; //0.0-1.0
        getWindow().setAttributes(lp);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }

    public void dismissBackgroundAlpha() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 1f; //0.0-1.0
        getWindow().setAttributes(lp);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 600);
        intent.putExtra("outputY", 600);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 4);
    }


    //初始化设置信息
    private void setInfo() {
        String userId = sp.getString("userId", "no");
        if (!"no".equals(userId)) {
            Net net = new Net();
            net.url = API.MEMBER_URL;
            net.nameSpace = API.MEMBER_NAMESPACE;
            net.methodName = API.MEMBERINFO;
            Map<String, Object> map = new HashMap<>();
            map.put("userId", userId);
            net.parms = map;
            net.code = HUOQUINFO;
            getServer(net, this);
        }
    }


    //修改昵称提交
    private void setNickName(String name) {
        String userId = sp.getString("userId", "");
        if (!"".equals(userId)) {
            Net net = new Net();
            net.url = API.MEMBER_URL;
            net.nameSpace = API.MEMBER_NAMESPACE;
            net.methodName = API.NICKNAMESAVE;
            Map<String, Object> map = new HashMap<>();
            map.put("nickName", name);
            map.put("userId", userId);
            net.parms = map;
            net.code = NICKNAMESAVE;
            getServer(net, this);
        }
    }


    @Override
    public void onResponse(boolean flag, int code, String res) {
        if (flag && code == NICKNAMESAVE) {
            try {
                JSONObject object = new JSONObject(res);
                if (object.getBoolean("result")) {
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("nickName", tv_xgname.getText().toString().trim());
                    editor.commit();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        if(flag&&code==HUOQUINFO){
            try {
                JSONObject object = new JSONObject(res);
                String nickName =object.getString("nickName");
                String account = object.getString("account");
                String imageurl = object.getString("headImg");
                tv_xgname.setText(nickName);
                et_phoneNumber.setText("手机号:" + account);
                if(!"".equals(imageurl)&&imageurl!=null){
                    Picasso.with(getApplicationContext()).load(imageurl).error(R.drawable.wd_del).transform(new CircleImage()).placeholder(R.drawable.wd_del).into(iv_touxiang);
                }else {
                    Picasso.with(getApplicationContext()).load(R.drawable.wd_del).into(iv_touxiang);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (flag && code == UPLOADHEAD) {
            try {
                JSONObject object = new JSONObject(res);
                if (object.getBoolean("result")) {
                    iv_touxiang.setImageBitmap(photo);
                }
                Toast.makeText(getApplicationContext(),object.getString("msg"),Toast.LENGTH_SHORT).show();
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }



}
